package com.lagou.edu.controller;

import com.alibaba.fastjson.JSON;
import com.lagou.edu.pojo.Order;
import com.lagou.edu.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class OrderController {

	@Autowired
	private OrderService orderService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@RequestMapping("/index")
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/createOrder", method = RequestMethod.POST)
	public String createOrder() {
		String orderId = new SimpleDateFormat("yyyyMMddHHmmssS").format(new Date());
		Order order = new Order();
		order.setOrderId(orderId);
		order.setState(1);
		orderService.addOrder(order);
		//发送消息
		rabbitTemplate.convertAndSend("ex.pay", "pay", orderId);
		Map<String,Object> map = new HashMap<>();
		map.put("code", "1");
		map.put("msg", "成功");
		map.put("orderId", orderId);
		return JSON.toJSONString(map);
	}

	@RequestMapping(value = "/payOrder", method = RequestMethod.POST)
	public String payOrder(String orderId) {
		Map<String,Object> map = new HashMap<>();
		Order order = orderService.selectOrderByOrderId(orderId);
		String msg= "";
		String code = "1" ;
		if (order.getState() == 1) {
			orderService.updateOrder(order.getOrderId(),2);
			msg = "成功";
		} else if (order.getState() == 2) {
			msg = "已支付，不能重复支付";
			code = "2";
		} else {
			msg = "已超时，支付已取消";
			code = "3";
		}
		map.put("msg", msg);
		map.put("code", code);
		return JSON.toJSONString(map);
	}


	@RequestMapping("getCancelOrders")
	public List<Order> getCancelOrders() {
		List<Order> payOrders = orderService.selectOrderList(3);
		return payOrders;
	}

}
